package com.example.parallelandroid;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.example.parallelandroid.entity.User;
import com.example.parallelandroid.utils.EncryptUtils;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class LoginActivity extends AppCompatActivity implements View.OnClickListener{
    EditText edtPhone,edtPassword;
    CheckBox rememberPassword,autoLogin;
    Button btnLogin;
    TextView forgetPassword,codeLogin;
    SharedPreferences sharedPreferences;
    Handler handler = new Handler(){
        @SuppressLint("HandlerLeak")
        @Override
        public void handleMessage(@NonNull Message msg) {
            int tag = msg.what;
            switch (tag){
                case 1:
                    SharedPreferences.Editor editor = sharedPreferences.edit();
                    String phone = edtPhone.getText().toString().trim();
                    String code = (String) msg.obj;
                    if("200".equals(code)){
                        editor.putString("phone",phone);
                        if(rememberPassword.isChecked()){
                            editor.putString("password", edtPassword.getText().toString());
                            editor.putBoolean("isRemember",true);
                        }else{
                            editor.putBoolean("isRemember",false);
                            editor.remove("password");
                        }
                        if (autoLogin.isChecked()){//选中自动登录
                            editor.putBoolean("isAutoLogin",true);
                        }else {
                            editor.putBoolean("isAutoLogin",false);
                        }
                        editor.commit();//提交
                        Intent intent = new Intent(LoginActivity.this,MainFromActivity.class);
                        startActivity(intent);
                        Constant.logger.info("Jump from LoginActivity to MainFromActivity");
                    }else{
                        Toast.makeText(LoginActivity.this, "用户名或密码错误", Toast.LENGTH_LONG).show();
                    }
            }
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        sharedPreferences = getSharedPreferences("user",
                MODE_PRIVATE);
        getView();

        setDate();
    }

    private void setDate() {
        Boolean isRemember = sharedPreferences.
                getBoolean("isRemember", false);
        String phone = sharedPreferences.
                getString("phone","");
        edtPhone.setText(phone);
        if (isRemember){
            String password = sharedPreferences.
                    getString("password","");
            //将数据显示到界面
            edtPassword.setText(password);
            rememberPassword.setChecked(true);//选中记住密码
        }
        return;
    }

    private void getView() {
        edtPassword = findViewById(R.id.edt_password);
        edtPhone = findViewById(R.id.edt_phone);
        rememberPassword = findViewById(R.id.remember_password);
        autoLogin = findViewById(R.id.auto_login);
        btnLogin = findViewById(R.id.btn_login);
        btnLogin.setOnClickListener(this::onClick);
        forgetPassword = findViewById(R.id.forget_password);
        forgetPassword.setOnClickListener(this::onClick);
        codeLogin = findViewById(R.id.code_login);
        codeLogin.setOnClickListener(this::onClick);
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        switch (id){
            case R.id.btn_login:
                String phone = edtPhone.getText().toString().trim();
                String password = edtPassword.getText().toString().trim();
                if (TextUtils.isEmpty(phone)){
                    Toast.makeText( LoginActivity.this,"请输入手机号码",Toast.LENGTH_LONG).show();
                }else if (TextUtils.isEmpty(password)) {
                    Toast.makeText(LoginActivity.this, "请输入密码", Toast.LENGTH_LONG).show();
                }else{
                    SharedPreferences.Editor editor = sharedPreferences.edit();
                    editor.putString("password",password);
                    editor.commit();
                    checkLogin(phone, EncryptUtils.encrypt(password));
                }
                break;
            case R.id.forget_password:
                Intent intent = new Intent(LoginActivity.this,ForgetPasswordActivity.class);
                startActivity(intent);
                Constant.logger.info("Jump from LoginActivity to ForgetPasswordActivity");
                break;
            case R.id.code_login:
                Intent intent1 = new Intent(LoginActivity.this,MainActivity.class);
                startActivity(intent1);
                Constant.logger.info("Jump from LoginActivity to MainActivity");
                break;
        }
    }
    private void checkLogin(String phone, String password) {
        Constant.logger.info("开始向服务端传输账号密码 userName=" + phone);
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url(Constant.BASE_URL+"user/checkPassword?userName=" + phone + "&password=" + password)
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new okhttp3.Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                Constant.logger.warn("向服务端传输账号密码: 失败", e);
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                String json = response.body().string();
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(json);
                    Gson gson = new Gson();
                    String code = jsonObject.getString("code");
                    String msg = jsonObject.getString("msg");
                    Constant.logger.info("服务端Response: " + msg);
                    String jsonStr = jsonObject.getString("data");
                    if(!(jsonStr == null || "".equals(jsonStr) || "null".equals(jsonStr))){
                        User user = gson.fromJson(jsonStr,User.class);
                        SharedPreferences.Editor editor = sharedPreferences.edit();
                        Constant.logger.debug("userId = " + user.getUserId());
                        editor.putString("userId",user.getUserId());
                        editor.commit();
                    }
                    Message message = new Message();
                    message.what = 1;
                    message.obj = code;
                    handler.sendMessage(message);
                } catch (JSONException e) {
                    Constant.logger.info("解析服务端Response: 失败", e);
                }
            }
        });
    }
}